'use strict'

import { app, BrowserWindow, ipcMain, Menu, nativeImage, Tray } from 'electron'
import '../renderer/store'
import path from 'path'

/**
 * Set `__static` path to static files in production
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
 */
if (process.env.NODE_ENV !== 'development') {
  global.__static = require('path')
    .join(__dirname, '/static')
    .replace(/\\/g, '\\\\')
}

// 是否开发模式
const IS_DEV = process.env.NODE_ENV === 'development'

let mainWindow

const winURL = IS_DEV
  ? `http://localhost:9080`
  : `file://${__dirname}/index.html`

let appIcon, icon, tray

/**
 * 程序初始化
 */
function init() {
  appIcon = path.join(__static, './icons/logo.png')
  icon = path.join(__static, './icons/icon.ico')

  // 托盘功能
  tray = new Tray(nativeImage.createFromPath(appIcon))

  // 托盘tip
  tray.setToolTip('桌面工具箱')

  // 托盘右键菜单
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '退出程序',
      click: () => {
        app.quit()
      }
    }
  ])

  tray.setContextMenu(contextMenu)
}
/**
 * 创建主窗口
 */
function createWindow() {
  init()
  mainWindow = new BrowserWindow({
    height: 500,
    width: 800,
    minHeight: 500,
    minWidth: 800,
    x: 1000,
    y: 100,
    // 窗体缩放
    titleBarStyle: 'hidden',
    // 隐藏边框
    frame: false,
    // 背景透明
    // transparent: IS_DEV,
    // 置顶
    // alwaysOnTop: true,
    // 任务栏图标
    icon,
    webPreferences: {
      devTools: IS_DEV,
      nodeIntegration: true,
      enableRemoteModule: false
    }
  })

  mainWindow.loadURL(winURL)

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})

/**
 * 程序退出前销毁托盘图标
 */
app.on('before-quit', function (evt) {
  tray.destroy()
})

/**
 * 最小化
 */
ipcMain.on('windows-win', event => {
  mainWindow.minimize()
})

/**
 * 最大化和还原窗口
 */
ipcMain.on('windows-max', (event, status) => {
  status || !mainWindow.isMaximized()
    ? mainWindow.maximize()
    : mainWindow.restore()
})

/**
 * 关闭程序
 */
ipcMain.on('windows-close', event => {
  app.quit()
})

/**
 * Auto Updater
 *
 * Uncomment the following code below and install `electron-updater` to
 * support auto updating. Code Signing with a valid certificate is required.
 * https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
 */

/*
import { autoUpdater } from 'electron-updater'

autoUpdater.on('update-downloaded', () => {
  autoUpdater.quitAndInstall()
})

app.on('ready', () => {
  if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
 */
